package com.sddnytsh.body_buildingsystem.components

import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.layout.wrapContentSize
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Delete
import androidx.compose.material.icons.filled.KeyboardArrowDown
import androidx.compose.material.icons.filled.KeyboardArrowUp
import androidx.compose.material.icons.filled.List
import androidx.compose.material.icons.outlined.ShoppingCart
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.Divider
import androidx.compose.material3.DropdownMenu
import androidx.compose.material3.DropdownMenuItem
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedButton
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import com.google.firebase.crashlytics.buildtools.reloc.com.google.common.reflect.TypeToken
import com.google.gson.Gson
import com.sddnytsh.body_buildingsystem.topic.FoodItem
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.RequestBody.Companion.toRequestBody
import org.json.JSONArray
import org.json.JSONObject

// 食物热量数据 ( 需要从后端获取的数据 )
val foodCalories = mapOf(
    "苹果" to 52,
    "香蕉" to 89,
    "鸡胸肉" to 165,
    "米饭" to 130,
    "牛肉" to 250,
    "鸡蛋" to 155,
    "蛋糕" to 1000,
)

@Composable
fun Page2() {
    var selectedFood by remember { mutableStateOf("选择食物") }
    var weight by remember { mutableStateOf("") }
    var expanded by remember { mutableStateOf(false) }
    var showDialog by remember { mutableStateOf(false) }
    var totalCalories by remember { mutableStateOf(0) }
    var foodList by remember { mutableStateOf<List<FoodItem>>(emptyList()) }
    var showHistoryDialog by remember { mutableStateOf(false) }
    var historyList by remember { mutableStateOf<List<FoodHistoryItem>>(emptyList()) }
    var isLoadingHistory by remember { mutableStateOf(false) }

    Column(
        modifier = Modifier
            .fillMaxSize()
            .background(Color.White)
    ) {
        // 顶部栏
        Box(
            modifier = Modifier
                .fillMaxWidth()
                .height(56.dp)
                .background(Color.Blue)
        ) {
            Text(
                text = "食物热量计算器",
                color = Color.White,
                modifier = Modifier.align(Alignment.Center)
            )

            // 修复：将历史记录按钮放在Box内部，使用正确的对齐方式
            IconButton(
                onClick = {
                    showHistoryDialog = true
                    isLoadingHistory = true
                    loadHistory(historyList) { newHistoryList ->
                        historyList = newHistoryList
                        isLoadingHistory = false
                    }
                },
                modifier = Modifier
                    .align(Alignment.CenterEnd) // 直接使用Alignment.CenterEnd，不需要转换
                    .padding(end = 8.dp)
            ) {
                Icon(
                    imageVector = Icons.Default.List,
                    contentDescription = "历史记录",
                    tint = Color.White
                )
            }
        }

        // 主要内容区域
        Box(modifier = Modifier.weight(1f)) {
            if (foodList.isNotEmpty()) {
                Column(
                    modifier = Modifier
                        .fillMaxSize()
                        .padding(16.dp)
                ) {
                    Text(
                        text = "已添加的食物:",
                        modifier = Modifier.padding(bottom = 16.dp)
                    )

                    LazyColumn(
                        modifier = Modifier.weight(1f)
                    ) {
                        items(foodList) { food ->
                            FoodListItem(
                                food = food,
                                onRemove = {
                                    foodList = foodList - food
                                    totalCalories -= food.calories
                                }
                            )
                            Divider(modifier = Modifier.padding(vertical = 8.dp))
                        }
                    }

                    Button(
                        onClick = {
                            saveFoodListToHistory(foodList) { success ->
                                if (success) {
                                    // 清空当前列表
                                    foodList = emptyList()
                                    totalCalories = 0
                                }
                            }
                        },
                        modifier = Modifier
                            .fillMaxWidth()
                            .padding(top = 16.dp),
                        colors = ButtonDefaults.buttonColors(Color.Red)
                    ) {
                        Text("保存并清空", color = Color.White)
                    }
                }
            } else {
                Column(
                    modifier = Modifier
                        .fillMaxSize()
                        .padding(16.dp),
                    horizontalAlignment = Alignment.CenterHorizontally,
                    verticalArrangement = Arrangement.Center
                ) {
                    Icon(
                        imageVector = Icons.Outlined.ShoppingCart,
                        contentDescription = "暂无食物",
                        modifier = Modifier.size(64.dp),
                        tint = Color.Gray
                    )
                    Spacer(modifier = Modifier.height(16.dp))
                    Text(
                        text = "暂无添加的食物",
                        style = MaterialTheme.typography.bodyLarge,
                        color = Color.Gray
                    )
                    Text(
                        text = "点击底部按钮添加食物",
                        style = MaterialTheme.typography.bodyMedium,
                        color = Color.LightGray
                    )
                }
            }
        }

        // 底部栏
        Box(
            modifier = Modifier
                .fillMaxWidth()
                .height(72.dp)
                .background(Color(0xFFF5F5F5))
                .padding(horizontal = 16.dp)
        ) {
            Row(
                modifier = Modifier
                    .fillMaxSize(),
                horizontalArrangement = Arrangement.SpaceBetween,
                verticalAlignment = Alignment.CenterVertically
            ) {
                Text(
                    text = "总计: $totalCalories 大卡",
                    style = MaterialTheme.typography.bodyLarge.copy(fontWeight = FontWeight.Bold),
                )

                Button(
                    onClick = { showDialog = true },
                    colors = ButtonDefaults.buttonColors(Color.Blue)
                ) {
                    Text("添加食物", color = Color.White)
                }
            }
        }
    }

    // 添加食物的对话框
    if (showDialog) {
        AlertDialog(
            onDismissRequest = { showDialog = false },
            title = {
                Text("添加食物")
            },
            text = {
                Column {
                    // 食物选择下拉菜单
                    Box(
                        modifier = Modifier
                            .fillMaxWidth()
                            .wrapContentSize(Alignment.TopStart)
                    ) {
                        OutlinedButton(
                            onClick = { expanded = true },
                            modifier = Modifier
                                .fillMaxWidth()
                                .height(56.dp),
                            colors = ButtonDefaults.outlinedButtonColors()
                        ) {
                            Text(
                                selectedFood,
                                modifier = Modifier.weight(1f),
                                textAlign = TextAlign.Start
                            )
                            Icon(
                                imageVector = if (expanded) Icons.Filled.KeyboardArrowUp else Icons.Filled.KeyboardArrowDown,
                                contentDescription = "下拉菜单"
                            )
                        }

                        DropdownMenu(
                            expanded = expanded,
                            onDismissRequest = { expanded = false },
                            modifier = Modifier.width(280.dp)
                        ) {
                            foodCalories.keys.forEach { food ->
                                DropdownMenuItem(
                                    text = { Text(food) },
                                    onClick = {
                                        selectedFood = food
                                        expanded = false
                                    }
                                )
                            }
                        }
                    }

                    Spacer(modifier = Modifier.height(16.dp))

                    // 重量输入
                    OutlinedTextField(
                        value = weight,
                        onValueChange = { weight = it },
                        label = { Text("请输入克数 (g)") },
                        singleLine = true,
                        modifier = Modifier.fillMaxWidth(),
                        keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number)
                    )
                }
            },
            confirmButton = {
                Button(
                    onClick = {
                        if (selectedFood != "选择食物" && weight.isNotBlank()) {
                            val weightValue = weight.toIntOrNull() ?: 0
                            val caloriePer100g = foodCalories[selectedFood] ?: 0
                            val calories = (weightValue * caloriePer100g) / 100

                            val newFood = FoodItem(selectedFood, weightValue, calories)
                            foodList = foodList + newFood
                            totalCalories += calories

                            // 重置表单
                            selectedFood = "选择食物"
                            weight = ""
                            showDialog = false
                        }
                    },
                    enabled = selectedFood != "选择食物" && weight.isNotBlank() && weight.toIntOrNull() != null
                ) {
                    Text("确认添加")
                }
            },
            dismissButton = {
                TextButton(
                    onClick = { showDialog = false }
                ) {
                    Text("取消")
                }
            }
        )
    }

    // 历史记录对话框
    if (showHistoryDialog) {
        AlertDialog(
            onDismissRequest = { showHistoryDialog = false },
            title = {
                Text("历史记录")
            },
            text = {
                if (isLoadingHistory) {
                    Box(
                        modifier = Modifier
                            .fillMaxWidth()
                            .height(200.dp),
                        contentAlignment = Alignment.Center
                    ) {
                        CircularProgressIndicator()
                    }
                } else if (historyList.isEmpty()) {
                    Box(
                        modifier = Modifier
                            .fillMaxWidth()
                            .height(200.dp),
                        contentAlignment = Alignment.Center
                    ) {
                        Text("暂无历史记录")
                    }
                } else {
                    Column(
                        modifier = Modifier
                            .fillMaxWidth()
                            .height(400.dp)
                    ) {
                        LazyColumn {
                            items(historyList) { historyItem ->
                                HistoryListItem(historyItem = historyItem)
                                Divider(modifier = Modifier.padding(vertical = 4.dp))
                            }
                        }
                    }
                }
            },
            confirmButton = {
                Button(
                    onClick = { showHistoryDialog = false }
                ) {
                    Text("关闭")
                }
            }
        )
    }
}

@Composable
fun FoodListItem(food: FoodItem, onRemove: () -> Unit) {
    Row(
        modifier = Modifier
            .fillMaxWidth()
            .padding(vertical = 8.dp),
        verticalAlignment = Alignment.CenterVertically,
        horizontalArrangement = Arrangement.SpaceBetween
    ) {
        Column(modifier = Modifier.weight(1f)) {
            Text(
                text = food.name,
                style = MaterialTheme.typography.bodyLarge.copy(fontWeight = FontWeight.Medium)
            )
            Text(
                text = "${food.weight}g - ${food.calories}大卡",
                style = MaterialTheme.typography.bodyMedium,
                color = Color.Gray
            )
        }

        IconButton(
            onClick = onRemove,
            modifier = Modifier.size(24.dp)
        ) {
            Icon(
                imageVector = Icons.Default.Delete,
                contentDescription = "删除",
                tint = Color.Red
            )
        }
    }
}

@Composable
fun HistoryListItem(historyItem: FoodHistoryItem) {
    Column(
        modifier = Modifier
            .fillMaxWidth()
            .padding(vertical = 8.dp)
    ) {
        Text(
            text = "记录 ID: ${historyItem.id}",
            style = MaterialTheme.typography.bodySmall,
            color = Color.Gray
        )
        Text(
            text = "食物: ${historyItem.foodItems.joinToString { it.name }}",
            style = MaterialTheme.typography.bodyMedium
        )
        Text(
            text = "总热量: ${historyItem.foodItems.sumOf { it.calories }} 大卡",
            style = MaterialTheme.typography.bodyMedium.copy(fontWeight = FontWeight.Bold)
        )
    }
}

// 保存食物列表到历史记录
fun saveFoodListToHistory(foodList: List<FoodItem>, onResult: (Boolean) -> Unit) {
    CoroutineScope(Dispatchers.IO).launch {
        try {
            // 替换为您的实际API端点
            val url = "https://10.203.132.164:8082/api/food-info"

            val client = OkHttpClient()

            // 创建请求体
            val json = JSONObject()
            val foodArray = JSONArray()

            foodList.forEach { food ->
                val foodJson = JSONObject()
                foodJson.put("name", food.name)
                foodJson.put("weight", food.weight)
                foodJson.put("calories", food.calories)
                foodArray.put(foodJson)
            }

            json.put("foods", foodArray)

            val requestBody = json.toString().toRequestBody("application/json".toMediaType())

            val request = Request.Builder()
                .url(url)
                .post(requestBody)
                .build()

            val response = client.newCall(request).execute()

            withContext(Dispatchers.Main) {
                onResult(response.isSuccessful)
            }
        } catch (e: Exception) {
            withContext(Dispatchers.Main) {
                onResult(false)
            }
        }
    }
}

// 加载历史记录
fun loadHistory(currentHistory: List<FoodHistoryItem>, onResult: (List<FoodHistoryItem>) -> Unit) {
    CoroutineScope(Dispatchers.IO).launch {
        try {
            // 替换为您的实际API端点
            val url = "https://10.203.132.164:8082/api/food-info"

            val client = OkHttpClient()
            val request = Request.Builder()
                .url(url)
                .build()

            val response = client.newCall(request).execute()

            if (response.isSuccessful) {
                val responseBody = response.body?.string()
                // 解析JSON响应为历史记录列表
                // 这里需要根据您的API响应格式进行解析
                val gson = Gson()
                val type = object : TypeToken<List<FoodHistoryItem>>() {}.type
                val historyList = gson.fromJson<List<FoodHistoryItem>>(responseBody, type)

                withContext(Dispatchers.Main) {
                    onResult(historyList)
                }
            } else {
                withContext(Dispatchers.Main) {
                    onResult(emptyList())
                }
            }
        } catch (e: Exception) {
            withContext(Dispatchers.Main) {
                onResult(emptyList())
            }
        }
    }
}

// 历史记录数据类
data class FoodHistoryItem(
    val id: Int,
    val foodItems: List<FoodItem>
)